﻿using JNPF.Basics.Logic;
using JNPF.Basics.Models;
using JNPF.Basics.Models.Extend.Dtos.TableExample;
using JNPF.Basics.Models.Extend.Model;
using JNPF.Utils;
using JNPF.Utils.Controller;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JNPF.Basics.Controller
{
    /// <summary>
    /// 表格示例数据
    /// 版 本：V2.6.200509
    /// 版 权：引迈信息技术有限公司（https://www.yinmaisoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2018-10-26 
    /// </summary>
    [Route("api/Extend/[controller]")]
    public class TableExampleController : BaseApiController
    {
        private TableExampleBll tableExampleBll = new TableExampleBll();
        private ProvinceBll provinceBll = new ProvinceBll();
        private UserBll userBll = new UserBll();
        private DictionaryDataBll dictionaryDataBll = new DictionaryDataBll();

        #region GET
        /// <summary>
        /// 获取表格数据列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseResult> GetList([FromQuery] PageInput input)
        {
            var data = await tableExampleBll.GetList(input);
            data.list.ForEach(x => x.Registrant = userBll.GetUserName(x.Registrant));
            var output = new PageResult()
            {
                list = data.list.MapToList<TableExampleListOutput>(),
                pagination = data.pagination
            };
            return Success(output);
        }

        /// <summary>
        /// 列表（树形表格）
        /// </summary>
        /// <param name="typeId"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("ControlSample/{typeId}")]
        public async Task<ResponseResult> GetList(string typeId, PageInput input)
        {
            var data = await tableExampleBll.GetList(typeId, input);
            var output = new PageResult()
            {
                list = data.list.MapToList<TableExampleListOutput>(),
                pagination = data.pagination
            };
            return Success(output);
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("All")]
        public async Task<ResponseResult> GetListAll(KeywordInput input)
        {
            var data = await tableExampleBll.GetList();
            if (input.keyword.IsNotEmptyOrNull())
            {
                data = data.FindAll(m => m.ProjectCode.Contains(input.keyword) || m.ProjectName.Contains(input.keyword) || m.CustomerName.Contains(input.keyword));
            }
            var output = data.MapToList<TableExampleAllOutput>();
            output.ForEach(x => x.registrant = userBll.GetUserName(x.registrant));
            return Success(new { list = output });
        }

        /// <summary>
        /// 获取延伸扩展列表(行政区划)
        /// </summary>
        /// <returns></returns>
        [HttpGet("IndustryList")]
        public async Task<ResponseResult> GetIndustryList()
        {
            var data = (await provinceBll.GetList("-1")).MapToList<TableExampleIndustryListOutput>();
            return Success(new { list = data });
        }

        /// <summary>
        /// 获取城市信息列表(获取延伸扩展列表(行政区划))
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("CityList/{id}")]
        public async Task<ResponseResult> GetCityList(string id)
        {
            var data = (await provinceBll.GetList(id)).MapToList<TableExampleCityListOutput>();
            return Success(new { list = data });
        }

        /// <summary>
        /// 列表（表格树形）
        /// </summary>
        /// <returns></returns>
        [HttpGet("ControlSample/TreeList")]
        public async Task<ResponseResult> GetTreeList(string isTree)
        {
            var data = await dictionaryDataBll.GetList("d59a3cf65f9847dbb08be449e3feae16");
            var treeList = data.Select(x => new TableExampleTreeListOutput()
            {
                id = x.Id,
                parentId = x.ParentId,
                text = x.FullName,
                loaded = true,
                expanded = true,
                ht = x.MapTo<Dictionary<string, object>>()
            }).ToList();
            var output = isTree.IsNotEmptyOrNull() && "1".Equals(isTree) ? treeList.ToTree() : treeList;
            return Success(new { list = output });
        }

        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        [HttpGet, Route("{id}")]
        public async Task<ResponseResult> GetInfo(string id)
        {
            var data = (await tableExampleBll.GetInfo(id)).MapTo<TableExampleInfoOutput>();
            return Success(data);
        }

        /// <summary>
        /// 获取批注
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}/Actions/Postil")]
        public async Task<ResponseResult> GetPostil(string id)
        {
            var tableExampleEntity = await tableExampleBll.GetInfo(id);
            if (tableExampleEntity == null)
            {
                return Error("数据不存在");
            }
            return Success(new { postilJson = tableExampleEntity.PostilJson });
        }
        #endregion

        #region POST
        /// <summary>
        /// 删除
         /// </summary>
        /// <param name="id">主键值</param>
         /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ResponseResult> Delete(string id)
        {
            var entity = await tableExampleBll.GetInfo(id);
            if (entity != null)
            {
                await tableExampleBll.Delete(entity);
            }
            return Success("删除成功");
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="input">实体对象</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> Create([FromBody] TableExampleCrInput input)
        {
            var entity = input.MapTo<TableExampleEntity>();
            entity.CostAmount = entity.CostAmount == null ? 0 : entity.CostAmount;
            entity.TunesAmount = entity.TunesAmount == null ? 0 : entity.TunesAmount;
            entity.ProjectedIncome = entity.ProjectedIncome == null ? 0 : entity.ProjectedIncome;
            entity.Sign = "0000000";
            await tableExampleBll.Create(entity);
            return Success("创建成功");
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">实体对象</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ResponseResult> Update(string id, [FromBody] TableExampleUpInput input)
        {
            var entity = input.MapTo<TableExampleEntity>();
            entity.CostAmount = entity.CostAmount == null ? 0 : entity.CostAmount;
            entity.TunesAmount = entity.TunesAmount == null ? 0 : entity.TunesAmount;
            entity.ProjectedIncome = entity.ProjectedIncome == null ? 0 : entity.ProjectedIncome;
            await tableExampleBll.Update(id, entity);
            return Success("更新成功");
        }

        /// <summary>
        /// 更新标签
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">实体对象</param>
        /// <returns></returns>
        [HttpPut("UpdateSign/{id}")]
        public async Task<ResponseResult> UpdateSign(string id, [FromBody] TableExampleSignUpInput input)
        {
            var tableExampleEntity = await tableExampleBll.GetInfo(id);
            tableExampleEntity.Sign = input.sign;
            await tableExampleBll.Update(id, tableExampleEntity);
            return Success("更新成功");
        }

        /// <summary>
        /// 行编辑
        /// </summary>
        /// <param name="id"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut("{id}/Actions/RowsEdit")]
        public async Task<ResponseResult> RowEditing(string id, [FromBody] TableExampleRowUpInput input)
        {
            var entity = input.MapTo<TableExampleEntity>();
            entity.Id = id;
            entity.CostAmount = entity.CostAmount == null ? 0 : entity.CostAmount;
            entity.TunesAmount = entity.TunesAmount == null ? 0 : entity.TunesAmount;
            entity.ProjectedIncome = entity.ProjectedIncome == null ? 0 : entity.ProjectedIncome;
            await tableExampleBll.RowEditing(entity);
            return Success("更新成功");
        }


        /// <summary>
        /// 发送批注
        /// </summary>
        /// <param name="id"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("{id}/Postil")]
        public async Task<ResponseResult> SendPostil(string id, [FromBody] TableExamplePostilSendInput input)
        {
            var tableExampleEntity = await tableExampleBll.GetInfo(id);
            if (tableExampleEntity == null)
            {
                return Error("发送失败，数据不存在");
            }
            UserInfo userInfo = UserProvider.Instance.Get();
            var model = new PostilModel()
            {
                userId =userBll.GetUserName(userInfo.UserId),
                text = input.text,
                creatorTime = DateTime.Now
            };
            var list = new List<PostilModel>();
            list.Add(model);
            if (tableExampleEntity.PostilJson.IsNotEmptyOrNull())
            {
                list = list.Concat(tableExampleEntity.PostilJson.ToList<PostilModel>()).ToList();
            }
            var postilJson = list.ToJson();
            tableExampleEntity.PostilJson = postilJson;
            tableExampleEntity.PostilCount = list.Count;
            await tableExampleBll.Update(id, tableExampleEntity);
            return Success("发送成功");
        }

        /// <summary>
        /// 删除批注
        /// </summary>
        /// <param name="id">主键值</param>
        /// <param name="postParam">请求参数</param>
        /// <returns></returns>
        [HttpDelete("{id}/Postil/{index}")]
        public async Task<ResponseResult> DeletePostil(string id, int index)
        {
            var tableExampleEntity = await tableExampleBll.GetInfo(id);
            if (tableExampleEntity == null)
            {
                return Error("删除失败，数据不存在");
            }
            var list = tableExampleEntity.PostilJson.ToList<PostilModel>();
            list.Remove(list[index]);
            tableExampleEntity.PostilJson = list.ToJson();
            tableExampleEntity.PostilCount = list.Count;
            await tableExampleBll.Update(id, tableExampleEntity);
            return Success("删除成功");
        }
        #endregion
    }
}